<template>
  <Drawer
    v-model:show="modalShow"
    @close="clearFridgeSettingModal"
    class="Refrigerator-add-Drawer"
    :inner-height="'80vh'"
  >
    <template #header>
      <text class="drawer-title">{{ editItems ? '修改产品' : '添加新产品' }}</text>
    </template>
    <view class="Refrigerator-add" v-show="modalShow">
      <view class="tory-type">
        <view class="tory-title">品类</view>
        <view class="type-list">
          <view class="list-box" v-for="(items, index) in typeList" :key="index">
            <view
              class="list-items"
              :class="{
                active: payloadData.categoryId === items.id,
              }"
              @click="chooseToryType(items.id, items.name)"
            >
              {{ items.name }}
            </view>
          </view>
        </view>
      </view>
      <view class="tory-brand">
        <view class="tory-title">品牌</view>
        <view class="title-input">
          <input type="text" placeholder="品牌名称" v-model="payloadData.brand" />
        </view>
      </view>
      <view class="tory-num">
        <view class="tory-title">数量</view>
        <view class="num-box">
          <view class="reduce-box" @click="reduceCount" :class="{ inactive: payloadData.count <= 0 }">-</view>
          <view class="num-show">{{ payloadData.count }}</view>
          <view class="increase-show" @click="increaseCount" :class="{ inactive: payloadData.count >= 50 }">+</view>
        </view>
      </view>
      <view class="tory-date">
        <view class="tory-title">开封日期<text class="gray">（选填）</text></view>
        <view class="date-operate">
          <DatePicker
            class="date-picker"
            :modal-show="modalShow"
            @change="updateFirstUseDate"
            :eidit-show="initFirstUseDate"
          ></DatePicker>
        </view>
      </view>
      <view class="tory-quality">
        <view class="tory-title">保质期<text class="gray">（选填）</text></view>
        <div class="quality-operate">
          <picker-view
            indicator-style="height: 45px; max-width:128rpx; border: none;overflow: hidden;"
            indicator-class="picker-selected"
            class="quality-picker"
            :value="qulityIndex"
            @change="updateStorageDate"
          >
            <picker-view-column>
              <view
                class="item"
                v-for="(item, index) in qualityDate"
                :key="index"
                :class="{ 'active-text': qulityIndex[0] === index }"
                >{{ item.split('')[0] === '0' ? ` ${item.split('')[1]}` : item }}</view
              >
            </picker-view-column>
            <text class="tips">月</text>
          </picker-view>
        </div>
      </view>
    </view>
    <div class="footer-btn">
      <div class="btn-cancel" @click="clearFridgeSettingModal">取消</div>
      <div class="btn-confirm" @click="addTorly">确定</div>
    </div>
  </Drawer>
</template>
<script lang="ts" setup>
import { insertInventoryList, modifyInventoryList } from '@/api/refrigetorB'
import DatePicker from '@/common/datePicker.vue'
import Drawer from '@/common/drawer.vue'
import type { PayloadData, RefrigeratorBController } from '@/controller/RefrigeratorB/definition'
import { applianceControlTrack } from '@/dataReport/dataReportUtil'
const props = defineProps<{
  show: boolean
  control: RefrigeratorBController.Control
  editItems?: PayloadData
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
}>()
/**
 * 初始化
 */
const typeList = [
  {
    name: '爽肤水',
    id: 2,
  },
  {
    name: '乳液',
    id: 4,
  },
  {
    name: '精华',
    id: 5,
  },
  {
    name: '眼霜',
    id: 3,
  },
  {
    name: '面霜',
    id: 7,
  },
  {
    name: '面膜',
    id: 1,
  },
  {
    name: '口红',
    id: 6,
  },
  {
    name: '其他',
    id: 8,
  },
]
const qualityDate = ref<string[]>([])
const qulityIndex = ref<number[]>([0])
const payloadData = ref<PayloadData>({
  categoryId: -1,
  categoryName: '',
  brand: '',
  count: 1,
  firstUseDate: '',
  storageDate: '01',
})
function initQualityDate() {
  for (let i = 1; i <= 36; i++) {
    qualityDate.value.push((i < 10 ? '0' : '') + i)
  }
}
const modalShow = computed({
  get() {
    return props.show
  },
  set(show) {
    emit('update:show', show)
  },
})
watch(
  () => props.editItems,
  () => {
    if (props.editItems) {
      console.error(props.editItems)

      payloadData.value = props.editItems
      initEidtItems()
    } else {
      initPayloadData()
    }
  }
)
/**
 * 初始化编辑
 */

const initFirstUseDate = ref<string[]>([])
function initPayloadData() {
  payloadData.value = {
    categoryId: -1,
    categoryName: '',
    brand: '',
    count: 1,
    firstUseDate: '',
    storageDate: '01',
  }
}
function initEidtItems() {
  initFirstUseDate.value = payloadData.value.firstUseDate.split('-')
  nextTick(() => {
    qulityIndex.value = [qualityDate.value.findIndex((items) => items == payloadData.value.storageDate)]
  })
}

/**
 * 增删改查操作
 */
function clearFridgeSettingModal() {
  initPayloadData()
  qulityIndex.value = [0]
  emit('close')
}

async function addTorly() {
  if (!isChecked()) {
    return
  }

  if (props.editItems) {
    applianceControlTrack(
      () =>
        modifyInventoryList(props.control.store._datasource.haId, payloadData.value.id as number, payloadData.value),
      'modify_item',
      {
        item_info: {
          ...payloadData.value,
          id: payloadData.value.id,
        },
      },
      'RefrigeratorB.Detail.Modify.Item'
    )
  } else {
    applianceControlTrack(
      () => insertInventoryList(props.control.store._datasource.haId, payloadData.value),
      ' add_item',
      {
        item_info: {
          ...payloadData.value,
          id: payloadData.value.id,
        },
      },
      'RefrigeratorB.Detail.Add.Item'
    )
  }
  clearFridgeSettingModal()
}
/**
 * 选择化妆品类
 */
function chooseToryType(id: number, name: string) {
  payloadData.value.categoryId = id
  payloadData.value.categoryName = name
  changeQulitDate(id)
}
function changeQulitDate(id: number) {
  let date = 0
  if (id === 1 || id === 2 || id === 3 || id === 4 || id === 5) {
    date = 5
  } else if (id === 6) {
    date = 35
  } else {
    date = 11
  }
  qulityIndex.value[0] = date
  switchQuality()
}
/**
 * 化妆品数量
 */
// 数量递减
function reduceCount() {
  payloadData.value.count--
}
// 数量递增
function increaseCount() {
  payloadData.value.count++
}
/**
 * 开封日期
 */
function updateFirstUseDate(date: string) {
  payloadData.value.firstUseDate = date
}
/**
 * 保质期
 */
function updateStorageDate(e: any) {
  qulityIndex.value = e.detail.value
  switchQuality()
}
function switchQuality() {
  let quality = `${qualityDate.value[qulityIndex.value[0]]}`
  payloadData.value.storageDate = quality
}
watch(
  () => modalShow.value,
  () => {
    initQualityDate()
  }
)
/**
 * 必填项空判断
 */
function isChecked() {
  if (!payloadData.value.categoryName) {
    uni.showToast({
      icon: 'none',
      title: '请选择品类',
    })
    return false
  } else if (!payloadData.value.brand) {
    uni.showToast({
      icon: 'none',
      title: '请输入品牌名称',
    })
    return false
  } else {
    return true
  }
}
</script>
<style scoped lang="less">
/deep/ .Refrigerator-add-Drawer {
  .drawer-inner {
    max-height: 80vh !important;
  }
}
.inactive {
  pointer-events: none;
  opacity: 0.3;
}
.Refrigerator-add {
  margin-top: 42rpx;
  & > view {
    align-items: center;
  }
  .tory-title {
    color: var(--primary-petrol, #2d3746);
    font-size: 16px;
    font-weight: 600;
    letter-spacing: -0.5px;
    display: flex;
    align-items: center;
  }
  .tory-type {
    .type-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .list-box {
        width: 25%;
      }
      .list-items {
        width: 72px;
        height: 32px;
        flex-shrink: 0;
        background: var(--primary-grey-light, #f4f4f6);
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 36rpx;
        color: var(--primary-petrol, #2d3746);
        font-size: 28rpx;
        font-weight: 400;
        letter-spacing: -0.5px;
      }
    }
  }
  .tory-brand {
    display: flex;
    justify-content: space-between;
    margin-top: 28rpx;
    .title-input {
      height: 44rpx;
      flex: 1;
      border-bottom: 1rpx solid #e0e0e0;
      margin-left: 110rpx;
    }
  }
  .tory-num {
    display: flex;
    justify-content: space-between;
    margin-top: 76rpx;
    .num-box {
      display: flex;
      align-items: center;
      & > view {
        font-size: 32rpx;
        color: var(--primary-petrol, #2d3746);
        font-weight: 600;
      }
      .num-show {
        width: 64px;
        height: 32px;
        flex-shrink: 0;
        margin: 0 24rpx;
        background: #f4f4f6;
        display: flex;
        justify-content: center;
        align-items: center;
        letter-spacing: -0.5px;
      }
    }
  }
  .tory-date {
    display: flex;
    margin-top: 64rpx;
    align-items: center;
    .date-operate {
      flex: 1;
      display: flex;
      .date-picker {
        width: 100%;
        // height: 108rpx;
      }
    }
  }
  .tory-quality {
    margin-top: 64rpx;
    display: flex;
    align-items: center;
    .quality-operate {
      /deep/ .picker-selected {
        position: relative;
      }
      /deep/ .picker-selected::before {
        content: '';
        position: absolute;
        top: 0px;
        border: none;
      }
      /deep/ .picker-selected::after {
        content: '';
        position: absolute;
        bottom: 0;
        border: none;
      }
      .active-text {
        font-weight: 600;
        font-size: 32rpx;
        color: var(--primary-color);
        border: none;
        outline: none;
      }
      flex: 1;
      margin-left: 36rpx;
      height: 216rpx;
      .quality-picker {
        // width: 100%;
        width: 149rpx;
        height: 100%;
        .item {
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .tips {
          display: flex;
          align-items: center;
          margin-left: 12rpx;
        }
      }
    }
  }

  .gray {
    opacity: 0.4;
    font-size: 24rpx;
  }
}
.active {
  background: var(--primary-blue-medium, #408df2) !important;
  color: #fff !important;
}
.footer-btn {
  display: flex;
  width: calc(100vw - 64rpx);
  padding-top: 54rpx;
  position: relative;
  margin-top: 96rpx;
  &::after {
    display: block;
    content: '';
    position: absolute;
    top: 0;
    width: 100vw;
    height: 1rpx;
    background-color: rgba(233, 233, 237, 1);
    left: -32rpx;
  }
  & > view {
    width: 50%;
    display: flex;
    justify-content: center;
    text-align: center;
    font-size: 32rpx;
    font-weight: 600;
    letter-spacing: -0.429px;
  }
  .btn-confirm {
    color: #408df2;
  }
}
</style>
